<?php
/**
 * Created by PhpStorm.
 * User: zhaoye
 * Date: 2016/10/24
 * Time: 下午4:33
 */

namespace model;
use MongoDB\BSON\ObjectID;
use ZPHP\Core\Db;
use tool\Validation;
use ZPHP\Core\Log;
use tool\Easemob;

class Group extends Base{

    /**
     * 数据验证
     * @param $params
     * @return bool
     */
    public function createGroup_v($params)
    {
        $validation = new Validation();
        $name = $params['name'];
        $description = $params['description'];
        $owner = $params['owner'];
        if($validation->isEmpty($name) === false)
        {
            $this->msg = '名称不能为空';
            return false;
        }
        if($validation->isEmpty($description) === false)
        {
            $this->msg = '描述不能为空';
            return false;
        }
        if($validation->isEmpty($owner) === false)
        {
            $this->msg = '管理员不能为空';
            return false;
        }

        return true;
    }

    /**
     * 最大的人数
     * @param $maxusers
     * @return int
     */
    public function maxusers($maxusers,$type = 'group')
    {
        if($maxusers <= 0)
        {
            $maxusers = 200;
        }
        if($maxusers >= 2000)
        {
            if($type == 'group')
            {
                $maxusers = 2000;
            }
            else
            {
                $maxusers = 5000;
            }
        }
        return $maxusers;
    }

    /**
     * 创建一个群组聊天室
     * @param $request
     * @return bool
     */
    public function createGroup($params,$type = 'group')
    {
        if($this->createGroup_v($params) === false)
        {
            $this->code = 10001;
            //未通过验证
            return false;
        }
        if($type == 'group')
        {//群组
            $options['type'] = 'group';
        }
        else
        {//聊天室
            $params['public'] == true;
            $params['approval'] == false;
            $options['type'] = 'room';
        }
        $options['name'] = $params['name'];
        $options['description'] = $params['description'];
        $maxusers = isset($params['maxusers'])?$params['maxusers']:200;
        $options['public'] = $params['public'] == true?true:false;
        $options['approval'] = $params['approval'] == true?true:false;
        $options['owner'] = $params['owner'];
        $options['members'] = isset($params['members'])?$params['members']:[];
        $options['maxusers'] = $this->maxusers($maxusers,$type);
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($options['owner']);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        foreach($options['members'] as $v)
        {
            $res = yield $mModel->isExistsUser($v);
            if($res === false)
            {
                $this->code = $mModel->code;
                $this->msg = $mModel->msg;
                //未通过验证
                return false;
            }
        }
        $time = getMillisecond();
        $id = (string)new ObjectID();
        yield Db::collection('lqhn_groups')->add(['id'=>$id,'name'=>$options['name'],'description'=>$options['description'],'type'=>$options['type'],
            'maxusers'=>$options['maxusers'],'public'=>$options['public'],'membersonly'=>true,'owner'=>$options['owner'],'blacklist'=>[],
            'allowinvites'=>true,'admin'=>[],'members'=>$options['members'],'invite_need_confirm'=>true,'last_modified'=>$time,'created'=>$time]);
        if($type == 'group')
        {
            $_add = ['groupids'=>$id];
        }
        else
        {//聊天室
            $_add = ['roomids'=>$id];
        }
        yield Db::collection('lqhn_members')->where(['username'=>$options['owner']])->addToSet($_add);
        foreach($options['members'] as $v)
        {
            yield Db::collection('lqhn_members')->where(['username'=>$v])->addToSet($_add);
        }
        return ['id'=>$id];
    }

    /**
     * 修改群组信息
     * @param $request
     * @return bool
     */
    public function modifyGroupInfo($params,$type = 'group')
    {
        $id = $params['id'];
        $where = [];
        $where['id'] = $id;
        if($type == 'group')
        {
            $where['type'] = 'group';
        }
        else
        {
            $where['type'] = 'room';
        }
        Log::write(json_encode($where));
        $data = yield Db::collection('lqhn_groups')->where($where)->field('name,description,maxusers')->find();
        if(!is_array($data))
        {
            $this->code = 10002;
            $this->msg = 'ID不存在';
            return false;
        }
        isset($params['name'])?$options['name'] = $params['name']:$options['name'] = $data['name'];
        isset($params['maxusers'])?$options['maxusers'] = $params['maxusers']:$options['maxusers'] = $data['maxusers'];
        isset($params['description'])?$options['description'] = $params['description']:$options['description'] = $data['description'];
        $options['maxusers'] = $this->maxusers($options['maxusers'],$type);
        $time = getMillisecond();

        yield Db::collection('lqhn_groups')->where($where)->save(['name'=>$options['name'],'description'=>$options['description'],
            'maxusers'=>$options['maxusers'],'last_modified'=>$time]);
        return '';
    }

    /**
     * 获取一个或多个群组的详情
     * @param $request
     * @return bool
     */
    public function getGroupDetail($params,$type = 'group')
    {
        $ids = $params['ids'];
        $ids = implode(',',$ids);
        $where = [];
        $where['id'] =  ['in',$ids];
        if($type == 'group')
        {
            $where['type'] = 'group';
        }
        else
        {
            $where['type'] = 'room';
        }
        $data['list'] = yield Db::collection('lqhn_groups')->where($where)->field('id,name,description,public,membersonly,allowinvites,maxusers,owner,admin,members')->get();
        return $data;
    }

    /**
     * 删除群组
     * @param $request
     * @return bool
     */
    public function deleteGroup($params,$type = 'group')
    {
        $id = $params['id'];
        $where = [];
        $where['id'] = $id;
        if($type == 'group')
        {
            $_del = ['groupids'=>$id];
            $where['type'] = 'group';
        }
        else
        {
            $_del = ['roomids'=>$id];
            $where['type'] = 'room';
        }
            $data = yield Db::collection('lqhn_groups')->where($where)->field('owner,admin,members')->find();
        if(!is_array($data))
        {
            $this->code = 10002;
            $this->msg = 'ID不存在';
            return false;
        }
        yield Db::collection('lqhn_groups')->where($where)->delete();
        yield Db::collection('lqhn_members')->where(['username'=>$data['owner']])->pull($_del);
        foreach ($data['admin'] as $v)
        {
            yield Db::collection('lqhn_members')->where(['username'=>$v])->pull($_del);

        }
        foreach ($data['members'] as $v)
        {
            yield Db::collection('lqhn_members')->where(['username'=>$v])->pull($_del);

        }
        return '';
    }



    /**
     * 获取所有群组
     * @return bool
     */
    public function getGroups($params,$type = 'group')
    {
        $page = isset($params['page'])?$params['page']:1;
        $num = isset($params['num'])?$params['num']:10;
        $where = [];
        if($type == 'group')
        {
            $where['type'] = 'group';
        }
        else
        {
            $where['type'] = 'room';
        }
        //计算总页数
        $count = yield Db::collection('lqhn_groups')->where($where)->count();
        $data['totalPage'] = $totalPage = ceil($count/$num) <= 0?1:ceil($count/$num);
        //计算要获取第几页数据
        $page = $page >1 ? $page : 1;
        $currentPage = $totalPage > $page ? $page : $totalPage;
        $skip = ($currentPage-1)*$num;
        $data['currentPage'] = $currentPage;
        $list = yield Db::collection('lqhn_groups')->field('id,name,owner,admin,type,last_modified,members')->where($where)->limit($num,$skip)->get();
        $data['list'] = [];
        foreach($list as $v)
        {
            $v['member_count'] = count($v['members']);
            unset($v['members']);
            $data['list'][] = $v;
        }
        return $data;

    }

    /**
     * 获取所有群组成员
     * @return bool
     */
    public function getGroupUsers($params,$type = 'group')
    {
        $page = isset($params['page'])?$params['page']:1;
        $num = isset($params['num'])?$params['num']:1000;
        $id = $params['id'];
        $where = [];
        $where['id'] = $id;
        if($type == 'group')
        {
            $where['type'] = 'group';
        }
        else
        {
            $where['type'] = 'room';
        }
        $res = yield Db::collection('lqhn_groups')->where($where)->field('owner,admin,members')->find();
        if(!is_array($res))
        {
            $this->code = 10002;
            $this->msg = 'ID不存在';
            return false;
        }
        //计算总页数
        $count = count($res['members']);
        $data['members']['totalPage'] = $totalPage = ceil($count/$num) <= 0?1:ceil($count/$num);
        //计算要获取第几页数据
        $page = $page >1 ? $page : 1;
        $currentPage = $totalPage > $page ? $page : $totalPage;
        $skip = ($currentPage-1)*$num;
        $data['members']['currentPage'] = $currentPage;
        $data['owner'] = $res['owner'];
        $data['admin'] = $res['admin'];
        $data['members']['list'] = array_slice($res['members'],$skip,$num);
        return $data;

    }

    /**
     * 群组单个加人
     * @return bool
     */
    public function addGroupMember($params,$type = 'group')
    {
        $id = $params['id'];
        $username = $params['username'];
        $where['id'] = $id;
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        if($type == 'group')
        {
            $where['type'] = 'group';
            $_add = ['groupids'=>$id];
        }
        else
        {
            $where['type'] = 'room';
            $_add = ['roomids'=>$id];
        }
        $res = yield Db::collection('lqhn_groups')->where($where)->addToSet(['members'=>$username]);
        if(!$res)
        {
            $this->code = 20001;
            $this->msg = '已经存在该成员['.$username.']';
            //未通过验证
            return false;
        }
        yield Db::collection('lqhn_members')->where(['username' => $username])->addToSet($_add);
        return '';

    }


    /**
     * 群组批量加人
     * @return bool
     */

    public function addGroupMembers($params,$type = 'group')
    {
        $id = $params['id'];
        $usernames = $params['usernames'];
        $errordata = [];
        foreach($usernames as $v)
        {
            $res = yield $this->addGroupMember(['id'=>$id,'username'=>$v],$type);
            if($res === false)
            {
                $errordata[$v] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($errordata))
        {
            $this->code = 102;
            $this->msg = '部分数据新增失败，查看errordata详情';
            return $errordata;
        }
        return true;
    }

    /**
     * 群组单个减人
     * @return bool
     */
    public function deleteGroupMember($params,$type = 'group')
    {
        $id = $params['id'];
        $username = $params['username'];
        $where = [];
        $where['id'] = $id;
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        if($type == 'group')
        {
            $where['type'] = 'group';
            $_del = ['groupids'=>$id];
        }
        else
        {
            $where['type'] = 'room';
            $_del = ['roomids'=>$id];
        }
        $res = yield Db::collection('lqhn_groups')->where($where)->pull(['members'=>$username]);
        if(!$res)
        {
            $this->code = 20002;
            $this->msg = '不存在该成员['.$username.']';
            //未通过验证
            return false;
        }
        yield Db::collection('lqhn_members')->where(['username' => $username])->pull($_del);
        return '';

    }

    /**
     * 群组批量加人
     * @return bool
     */

    public function deleteGroupMembers($params,$type = 'group')
    {
        $id = $params['id'];
        $usernames = $params['usernames'];
        $errordata = [];
        foreach($usernames as $v)
        {
            $res = yield $this->deleteGroupMember(['id'=>$id,'username'=>$v],$type);
            if($res === false)
            {
                $errordata[$v] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($errordata))
        {
            $this->code = 106;
            $this->msg = '部分数据删除失败，查看errordata详情';
            return $errordata;
        }
        return true;
    }

    /**
     * 获取一个用户参与的所有群组
     * @return bool
     */
    public function getGroupsForUser($params,$type = 'group')
    {
        $username = $params['username'];
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        if($type == 'group')
        {
            $field = 'groupids';
        }
        else
        {
            $field = 'roomids';
        }
        $res = yield Db::collection('lqhn_members')->where(['username' => $username])->field($field)->find();
//        $ids = implode(',',$res[$field]);
        $ids = $res[$field];
        $where = [];
        $where['id'] = ['in',$ids];
        if($type == 'group')
        {
            $where['type'] = 'group';
        }
        else
        {
            $where['type'] = 'room';
        }
        $data = yield Db::collection('lqhn_groups')->where($where)->field('id,name')->get();
        return $data;

    }

    /**
     * 群组转让
     * @return bool
     */
    public function changeGroupOwner($params,$type = 'group')
    {
        $username = $params['newowner'];
        $id = $params['id'];
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        $_data = yield Db::collection('lqhn_groups')->where(['id' => $id])->field('owner,admin,members')->find();
        if(!is_array($_data))
        {
            $this->code = 10002;
            $this->msg = 'ID不存在';
            return false;
        }
        $tag = false;
        if(in_array($username,$_data['admin']))
        {
            $tag = true;
            yield Db::collection('lqhn_groups')->where(['id' => $id])->pull(['admin'=>$username]);
        }
        if(in_array($username,$_data['members']))
        {
            $tag = true;
            yield Db::collection('lqhn_groups')->where(['id' => $id])->pull(['members'=>$username]);
        }
        if($tag === false)
        {
            $this->code = 10002;
            $this->msg = '['.$username.']不是成员，无法转让';
            return false;
        }
        yield Db::collection('lqhn_groups')->where(['id' => $id])->save(['owner'=>$username]);
        yield Db::collection('lqhn_groups')->where(['id' => $id])->addToSet(['members'=>$_data['owner']]);

        return '';

    }


    /**
     * 群组黑名单单个加人
     * @return bool
     */
    public function addGroupBlackMember($params,$type = 'group')
    {
        $id = $params['id'];
        $username = $params['username'];
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        $res = yield Db::collection('lqhn_groups')->where(['id' => $id])->addToSet(['blacklist'=>$username]);
        if(!$res)
        {
            $this->code = 30001;
            $this->msg = '黑名单已经存在该成员['.$username.']';
            //未通过验证
            return false;
        }
        return '';

    }


    /**
     *
     * 群组黑名单批量加人
     * @return bool
     */

    public function addGroupBlackMembers($params,$type = 'group')
    {
        $id = $params['id'];
        $usernames = $params['usernames'];
        $errordata = [];
        foreach($usernames as $v)
        {
            $res = yield $this->addGroupBlackMember(['id'=>$id,'username'=>$v],$type);
            if($res === false)
            {
                $errordata[$v] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($errordata))
        {
            $this->code = 102;
            $this->msg = '部分数据新增失败，查看errordata详情';
            return $errordata;
        }
        return true;
    }

    /**
     * 群组黑名单单个减人
     * @return bool
     */
    public function deleteGroupBlackMember($params,$type = 'group')
    {
        $id = $params['id'];
        $username = $params['username'];
        $mModel = new Member();
        $res = yield $mModel->isExistsUser($username);
        if($res === false)
        {
            $this->code = $mModel->code;
            $this->msg = $mModel->msg;
            //未通过验证
            return false;
        }
        $res = yield Db::collection('lqhn_groups')->where(['id' => $id])->pull(['blacklist'=>$username]);
        if(!$res)
        {
            $this->code = 30002;
            $this->msg = '黑名单不存在该成员['.$username.']';
            //未通过验证
            return false;
        }
        return '';

    }


    /**
     *
     * 群组黑名单批量减人
     * @return bool
     */

    public function deleteGroupBlackMembers($params,$type = 'group')
    {
        $id = $params['id'];
        $usernames = $params['usernames'];
        $errordata = [];
        foreach($usernames as $v)
        {
            $res = yield $this->deleteGroupBlackMember(['id'=>$id,'username'=>$v],$type);
            if($res === false)
            {
                $errordata[$v] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($errordata))
        {
            $this->code = 106;
            $this->msg = '部分数据删除失败，查看errordata详情';
            return $errordata;
        }
        return true;
    }

    /**
     * 查询一个群组黑名单用户名列表
     * @return bool
     */
    public function getGroupBlackList($params,$type = 'group')
    {
        $id = $params['id'];
        $res = yield Db::collection('lqhn_groups')->where(['id' => $id])->field('blacklist')->find();
        if(!is_array($res))
        {
            $this->code = 10002;
            $this->msg = 'ID不存在';
            return false;
        }
        $data['count'] = count($res['blacklist']);
        $data['list'] = $res['blacklist'];
        return $data;

    }


}